import { WebSocketServer, WebSocket } from 'ws';
import { IncomingMessage } from 'http';
import jwt from 'jsonwebtoken';
import { pool } from '../config/database';
import { RowDataPacket } from 'mysql2';
import { JwtPayload } from '../types';
import axios from 'axios';
import { config } from '../config/env';
import { v4 as uuidv4 } from 'uuid';

// WebSocket消息类型定义
interface WebSocketMessage {
  type: 'message' | 'join' | 'leave' | 'typing' | 'stop_typing' | 'user_info' | 'chat_history' | 'error' | 'read_message' | 'message_read' | 'user_online' | 'user_offline' | 'ping' | 'pong' | 
        'ai_chat_request' | 'ai_chat_start' | 'ai_chat_chunk' | 'ai_chat_done' | 'ai_chat_error' | 'ai_chat_progress' | 'ai_chat_saved' | 'ai_chat_end' |
        'server_monitor_start' | 'server_monitor_update' | 'server_monitor_stop';
  data: any;
  timestamp?: number;
  userId?: number;
  userName?: string;
  isCustomerService?: boolean;
  targetUserId?: number; // 目标用户ID，用于一对一聊天
  sessionId?: string; // AI聊天会话ID
}

// 连接用户信息
interface ConnectedUser {
  ws: WebSocket;
  userId: number;
  userName: string;
  isCustomerService: boolean; // 保持字段名兼容性，实际表示isAdmin
  lastActivity: number;
  nickname?: string;
  avatar?: string;
}

// 聊天室管理
class ChatRoomManager {
  private users: Map<WebSocket, ConnectedUser> = new Map();
  private adminUsers: Set<WebSocket> = new Set(); // 管理员用户
  private normalUsers: Set<WebSocket> = new Set(); // 普通用户
  private userIdToWs: Map<number, Set<WebSocket>> = new Map(); // 用户ID到WebSocket的映射

  // 添加用户连接
  addUser(ws: WebSocket, userId: number, userName: string, isAdmin: boolean = false, userInfo?: {nickname?: string, avatar?: string}) {
    // 检查是否已存在该用户的连接
    const existingConnections = this.userIdToWs.get(userId);
    let isFirstConnection = true;
    
    if (existingConnections) {
      isFirstConnection = false;
      console.log(`⚠️ 用户 ${userName} (ID: ${userId}) 有多个连接，当前连接数: ${existingConnections.size}`);
      
      // 清理该用户的旧连接
      for (const oldWs of existingConnections) {
        if (oldWs !== ws && oldWs.readyState === WebSocket.OPEN) {
          console.log(`🔄 关闭用户 ${userName} 的旧连接`);
          oldWs.close();
        }
        this._removeUserFromMaps(oldWs);
      }
      existingConnections.clear();
      existingConnections.add(ws);
    } else {
      console.log(`🆕 用户 ${userName} (ID: ${userId}) 首次连接`);
      this.userIdToWs.set(userId, new Set([ws]));
    }

    const user: ConnectedUser = {
      ws,
      userId,
      userName,
      isCustomerService: isAdmin, // 保持字段名兼容性
      lastActivity: Date.now(),
      nickname: userInfo?.nickname,
      avatar: userInfo?.avatar
    };

    this.users.set(ws, user);

    if (isAdmin) {
      this.adminUsers.add(ws);
      console.log(`👑 管理员 ${userName} 已上线 (总连接数: ${this.users.size})`);
    } else {
      this.normalUsers.add(ws);
      console.log(`👤 用户 ${userName} 已连接 (总连接数: ${this.users.size})`);
      
      // 只有真正的首次连接才通知管理员
      if (isFirstConnection) {
        console.log(`📢 通知管理员：用户 ${userName} 首次上线`);
        this.notifyUserStatusChange(userId, true, {
          displayName: userName,
          userName: userName,
          nickname: userInfo?.nickname || null,
          avatar: userInfo?.avatar || null
        });
      } else {
        console.log(`🔄 用户 ${userName} 重新连接，不发送上线通知`);
      }
    }
  }

  // 私有方法：从映射中移除用户
  private _removeUserFromMaps(ws: WebSocket) {
    const user = this.users.get(ws);
    if (user) {
      // 从用户ID映射中移除
      const userConnections = this.userIdToWs.get(user.userId);
      if (userConnections) {
        userConnections.delete(ws);
        if (userConnections.size === 0) {
          this.userIdToWs.delete(user.userId);
        }
      }

      // 从角色分组中移除
      if (user.isCustomerService) {
        this.adminUsers.delete(ws);
      } else {
        this.normalUsers.delete(ws);
      }

      // 从主映射中移除
      this.users.delete(ws);
    }
  }

  // 移除用户连接
  removeUser(ws: WebSocket) {
    const user = this.users.get(ws);
    if (user) {
      console.log(`${user.isCustomerService ? '管理员' : '用户'} ${user.userName} 已断开连接 (剩余连接数: ${this.users.size - 1})`);
      
      // 如果是普通用户断开连接，检查该用户是否完全离线
      if (!user.isCustomerService) {
        // 先移除连接
        this._removeUserFromMaps(ws);
        
        // 检查该用户是否还有其他活跃连接
        const stillOnline = this.isUserOnline(user.userId);
        
        // 如果完全离线，通知管理员
        if (!stillOnline) {
          this.notifyUserStatusChange(user.userId, false, {
            displayName: user.userName,
            userName: user.userName,
            nickname: user.nickname || null,
            avatar: user.avatar || null
          });
        }
      } else {
        // 管理员断开连接，直接移除
        this._removeUserFromMaps(ws);
      }
    }
  }

  // 发送消息给指定用户
  sendToUser(ws: WebSocket, message: WebSocketMessage) {
    if (ws.readyState === WebSocket.OPEN) {
      message.timestamp = Date.now();
      ws.send(JSON.stringify(message));
    }
  }

  // 广播消息给所有管理员
  broadcastToAdmins(message: WebSocketMessage, excludeWs?: WebSocket) {
    const activeAdmins = Array.from(this.adminUsers).filter(ws => ws.readyState === WebSocket.OPEN);
    console.log(`开始向 ${activeAdmins.length} 个在线管理员广播消息`);
    
    activeAdmins.forEach(adminWs => {
      if (adminWs !== excludeWs) {
        this.sendToUser(adminWs, message);
      }
    });
  }

  // 广播消息给所有普通用户
  broadcastToUsers(message: WebSocketMessage, excludeWs?: WebSocket) {
    const activeUsers = Array.from(this.normalUsers).filter(ws => ws.readyState === WebSocket.OPEN);
    console.log(`开始向 ${activeUsers.length} 个在线用户广播消息`);
    
    activeUsers.forEach(userWs => {
      if (userWs !== excludeWs) {
        this.sendToUser(userWs, message);
      }
    });
  }

  // 发送消息给指定用户ID的所有连接
  sendToUserId(targetUserId: number, message: WebSocketMessage, excludeWs?: WebSocket) {
    const userConnections = this.userIdToWs.get(targetUserId);
    if (!userConnections) {
      console.log(`目标用户 ${targetUserId} 不在线`);
      return false;
    }

    let sentCount = 0;
    userConnections.forEach(ws => {
      if (ws !== excludeWs && ws.readyState === WebSocket.OPEN) {
        this.sendToUser(ws, message);
        sentCount++;
      }
    });

    console.log(`消息已发送给用户 ${targetUserId} 的 ${sentCount} 个连接`);
    return sentCount > 0;
  }

  // 获取用户是否在线
  isUserOnline(userId: number): boolean {
    const userConnections = this.userIdToWs.get(userId);
    if (!userConnections) return false;
    
    // 检查是否有活跃连接
    for (const ws of userConnections) {
      if (ws.readyState === WebSocket.OPEN) {
        return true;
      }
    }
    return false;
  }

  // 通知管理员用户状态变化
  notifyUserStatusChange(userId: number, isOnline: boolean, userInfo: any) {
    const type = isOnline ? 'user_online' : 'user_offline';
    const statusMessage: WebSocketMessage = {
      type: type as 'user_online' | 'user_offline',
      data: {
        userId: userId,
        userName: userInfo.displayName || userInfo.userName,
        nickname: userInfo.nickname,
        avatar: userInfo.avatar,
        isOnline: isOnline,
        timestamp: Date.now()
      },
      timestamp: Date.now()
    };

    console.log(`🔔 通知管理员: 用户 ${userInfo.displayName} ${isOnline ? '上线' : '下线'}`);
    this.broadcastToAdmins(statusMessage);
  }

  // 获取用户信息
  getUser(ws: WebSocket): ConnectedUser | undefined {
    return this.users.get(ws);
  }

  // 清理断开的连接
  cleanupDeadConnections() {
    const deadConnections: WebSocket[] = [];
    
    this.users.forEach((user, ws) => {
      if (ws.readyState !== WebSocket.OPEN) {
        deadConnections.push(ws);
      }
    });

    deadConnections.forEach(ws => {
      console.log(`清理断开的连接`);
      this.removeUser(ws);
    });

    return deadConnections.length;
  }

  // 清理非活跃连接
  cleanupInactiveConnections(timeout: number = 5 * 60 * 1000) {
    const now = Date.now();
    let cleanedCount = 0;
    const inactiveConnections: WebSocket[] = [];

    // 收集非活跃连接
    this.users.forEach((user, ws) => {
      if (now - user.lastActivity > timeout || ws.readyState !== WebSocket.OPEN) {
        inactiveConnections.push(ws);
      }
    });

    // 清理非活跃连接
    inactiveConnections.forEach(ws => {
      const user = this.getUser(ws);
      if (user) {
        console.log(`清理非活跃连接: ${user.userName} (超时: ${now - user.lastActivity > timeout}, 状态: ${ws.readyState})`);
        cleanedCount++;
        ws.terminate();
        this.removeUser(ws);
      }
    });

    return cleanedCount;
  }

  // 获取在线统计 - 按用户去重
  getStats() {
    // 清理断开的连接
    this.cleanupDeadConnections();

    // 按用户ID去重计算
    const uniqueAdminIds = new Set<number>();
    const uniqueUserIds = new Set<number>();

    this.users.forEach((user, ws) => {
      if (ws.readyState === WebSocket.OPEN) {
        if (user.isCustomerService) {
          uniqueAdminIds.add(user.userId);
        } else {
          uniqueUserIds.add(user.userId);
        }
      }
    });

    const uniqueAdminCount = uniqueAdminIds.size;
    const uniqueUserCount = uniqueUserIds.size;

    return {
      totalUsers: uniqueAdminCount + uniqueUserCount,
      adminCount: uniqueAdminCount,
      normalUserCount: uniqueUserCount,
      adminOnline: uniqueAdminCount > 0,
      // 调试信息
      totalConnections: this.users.size,
      uniqueUsers: this.userIdToWs.size
    };
  }

  // 获取详细的连接信息（调试用）
  getDetailedStats() {
    const connections: any[] = [];
    this.users.forEach((user, ws) => {
      connections.push({
        userId: user.userId,
        userName: user.userName,
        isAdmin: user.isCustomerService,
        readyState: ws.readyState,
        lastActivity: new Date(user.lastActivity).toISOString()
      });
    });

    return {
      totalConnections: this.users.size,
      uniqueUsers: this.userIdToWs.size,
      connections
    };
  }
}

const chatManager = new ChatRoomManager();

// 导出chatManager供其他模块使用
export function getChatManager() {
  return chatManager;
}

// AI聊天流式处理函数
// AI聊天处理逻辑已移至 POST /api/aiChat/stream 接口
// WebSocket只用于接收实时推送的AI回复
async function handleAiChatStream(
  ws: WebSocket, 
  userId: number, 
  message: string, 
  sessionId?: string
) {
  // 此函数已弃用，AI聊天处理逻辑已移至 POST 接口
  console.log('⚠️ handleAiChatStream函数已弃用，请使用POST /api/aiChat/stream接口');
  return;
  // 生成或使用现有的会话ID
  const currentSessionId = sessionId || uuidv4();
  
  // 创建请求取消控制器
  const abortController = new AbortController();
  
  // 发送AI聊天消息的辅助函数
  const sendAiMessage = (type: string, data: any) => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({
        type,
        data,
        sessionId: currentSessionId,
        timestamp: Date.now()
      }));
    }
  };

  try {
    // 发送开始事件
    sendAiMessage('ai_chat_start', {
      sessionId: currentSessionId,
      userMessage: message.trim(),
      timestamp: new Date().toISOString()
    });

    // 1. 先保存用户消息到数据库
    await pool.execute(
      "INSERT INTO ai_chat_records (user_id, session_id, message_type, content) VALUES (?, ?, ?, ?)",
      [userId, currentSessionId, 'user', message.trim()]
    );

    // 2. 获取会话历史消息（多轮会话上下文）
    const [historyRecords] = await pool.execute(
      `SELECT message_type, content, created_at 
       FROM ai_chat_records 
       WHERE user_id = ? AND session_id = ? 
       ORDER BY created_at ASC 
       LIMIT 10`,
      [userId, currentSessionId]
    ) as [RowDataPacket[], any];

    // 3. 构建多轮会话消息数组
    const messages = [
      {
        role: "system",
        content: "你是一个专业的装机指南助手，专门帮助用户选择电脑硬件、组装电脑和解决相关技术问题。请提供准确、实用的建议。"
      }
    ];

    // 添加历史消息到上下文
    for (const record of historyRecords) {
      if (record.message_type === 'user') {
        messages.push({
          role: "user",
          content: record.content
        });
      } else if (record.message_type === 'assistant') {
        messages.push({
          role: "assistant",
          content: record.content
        });
      }
    }

    // 发送连接进度
    sendAiMessage('ai_chat_progress', { message: '正在连接AI服务...' });

    // 4. 发送流式请求到DeepSeek
    const response = await axios.post(
      `${config.deepseek.base_url}/chat/completions`,
      {
        model: config.deepseek.model,
        messages: messages,
        temperature: 0.7,
        max_tokens: 2000,
        stream: true
      },
      {
        headers: {
          'Authorization': `Bearer ${config.deepseek.apiKey}`,
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream'
        },
        responseType: 'stream',
        timeout: 120000,
        signal: abortController.signal
      }
    );

    console.log('✅ AI流式连接成功');
    sendAiMessage('ai_chat_progress', { message: 'AI服务连接成功，开始生成回复...' });

    let fullResponse = '';
    let chunkCount = 0;

    // 处理DeepSeek流式数据
    let buffer = '';
    response.data.on('data', (chunk: Buffer) => {
      try {
        buffer += chunk.toString();
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';
        
        for (const line of lines) {
          const trimmedLine = line.trim();
          
          if (!trimmedLine || !trimmedLine.startsWith('data: ')) {
            continue;
          }

          const data = trimmedLine.slice(6).trim();
          console.log('🔍 收到AI流式数据:', data);
          
          if (data === '[DONE]') {
            console.log('🏁 AI流式响应完成');
            sendAiMessage('ai_chat_done', {
              fullResponse,
              chunkCount,
              timestamp: new Date().toISOString()
            });
            return;
          }

          if (data) {
            try {
              const parsed = JSON.parse(data);
              const delta = parsed.choices?.[0]?.delta;
              
              if (delta?.content) {
                const content = delta.content;
                fullResponse += content;
                chunkCount++;
                
                console.log(`📝 发送内容块 #${chunkCount}: "${content}"`);
                
                // 实时发送增量内容给前端
                sendAiMessage('ai_chat_chunk', {
                  content,
                  fullResponse,
                  chunkIndex: chunkCount,
                  timestamp: new Date().toISOString()
                });
              }
            } catch (parseError) {
              console.warn('❌ 解析AI流式数据失败:', parseError);
            }
          }
        }
      } catch (error) {
        console.error('💥 处理AI流式数据块时出错:', error);
      }
    });

    // 处理流结束
    response.data.on('end', async () => {
      console.log('📝 AI流式响应结束，准备保存到数据库');
      
      if (fullResponse.trim()) {
        try {
          await pool.execute(
            "INSERT INTO ai_chat_records (user_id, session_id, message_type, content) VALUES (?, ?, ?, ?)",
            [userId, currentSessionId, 'assistant', fullResponse.trim()]
          );
          console.log('✅ AI回复已保存到数据库');
          
          sendAiMessage('ai_chat_saved', {
            message: '对话已保存',
            timestamp: new Date().toISOString()
          });
        } catch (saveError) {
          console.error('❌ 保存AI回复失败:', saveError);
          sendAiMessage('ai_chat_error', {
            message: '保存失败，但回复已生成',
            error: saveError
          });
        }
      }

      // 结束AI聊天
      sendAiMessage('ai_chat_end', { message: 'AI对话完成' });
    });

    // 处理流错误
    response.data.on('error', (error: any) => {
      console.error('❌ AI流式数据错误:', error);
      sendAiMessage('ai_chat_error', {
        message: 'AI响应中断',
        error: error.message,
        timestamp: new Date().toISOString()
      });
    });

  } catch (error: any) {
    console.error('💥 AI聊天流式处理错误:', error);
    
    let userFriendlyMessage = "AI服务暂时不可用，请稍后重试";
    
    if (error.response) {
      const status = error.response.status;
      switch (status) {
        case 400:
          userFriendlyMessage = "请求格式错误，请检查您的输入";
          break;
        case 401:
          userFriendlyMessage = "API密钥无效，请联系管理员";
          break;
        case 429:
          userFriendlyMessage = "请求过于频繁，请稍后重试";
          break;
        case 500:
        case 502:
        case 503:
        case 504:
          userFriendlyMessage = "AI服务暂时不可用，请稍后重试";
          break;
      }
    }

    sendAiMessage('ai_chat_error', {
      message: userFriendlyMessage,
      error: error.message,
      timestamp: new Date().toISOString()
    });

    // 保存错误信息到数据库
    try {
      await pool.execute(
        "INSERT INTO ai_chat_records (user_id, session_id, message_type, content) VALUES (?, ?, ?, ?)",
        [userId, currentSessionId, 'assistant', `系统错误：${userFriendlyMessage}`]
      );
    } catch (dbError) {
      console.error("❌ 保存错误信息到数据库失败:", dbError);
    }

    sendAiMessage('ai_chat_end', { message: '请求处理完成' });
  }
}

// 保存聊天记录到数据库
async function saveChatMessage(
  userId: number, 
  message: string, 
  messageType: 'user' | 'customer_service' = 'user',
  targetUserId?: number
) {
  try {
    // 设置room_id以关联对话
    let roomId = null;
    if (messageType === 'customer_service' && targetUserId) {
      roomId = `user_${targetUserId}`;
    } else if (messageType === 'user') {
      roomId = `user_${userId}`;
    }

    // 使用NOW()函数让数据库根据连接时区自动处理时间
    await pool.query(
      `INSERT INTO chat_messages (user_id, message, message_type, room_id, created_at) 
       VALUES (?, ?, ?, ?, NOW())`,
      [userId, message, messageType, roomId]
    );
  } catch (error) {
    console.error('保存聊天记录失败:', error);
  }
}


// JWT验证
function verifyToken(token: string): JwtPayload | null {
  try {
    const secret = process.env.JWT_SECRET || 'your-secret-key';
    return jwt.verify(token, secret) as JwtPayload;
  } catch (error) {
    return null;
  }
}

// 标记消息为已读
async function markMessagesAsRead(userId: number, messageIds?: number[]) {
  try {
    // 使用NOW()函数让数据库根据连接时区自动处理时间
    let query = 'UPDATE chat_messages SET is_read = 1, updated_at = NOW() WHERE user_id != ? AND is_read = 0';
    let params = [userId];
    
    // 如果指定了特定消息ID，只标记这些消息
    if (messageIds && messageIds.length > 0) {
      query += ` AND id IN (${messageIds.map(() => '?').join(',')})`;
      params.push(...messageIds);
    }
    
    const [result] = await pool.query(query, params);
    return result;
  } catch (error) {
    console.error('标记消息已读失败:', error);
    return null;
  }
}

// 获取未读消息数量
async function getUnreadCount(userId: number) {
  try {
    const [result] = await pool.query(
      'SELECT COUNT(*) as count FROM chat_messages WHERE user_id != ? AND is_read = 0',
      [userId]
    ) as [RowDataPacket[], any];
    return result[0].count;
  } catch (error) {
    console.error('获取未读消息数量失败:', error);
    return 0;
  }
}

// 创建WebSocket服务器
export function createWebSocketServer(server: any) {
  const wss = new WebSocketServer({ 
    server,
    path: '/websocket'
  });

  wss.on('connection', async (ws: WebSocket, request: IncomingMessage) => {
    console.log('新的WebSocket连接');

    // 从URL参数中获取token
    const url = new URL(request.url || '', `http://${request.headers.host}`);
    const token = url.searchParams.get('token');

    if (!token) {
      ws.send(JSON.stringify({
        type: 'error',
        data: { message: '缺少认证token' }
      }));
      ws.close();
      return;
    }

    // 验证token
    const user = verifyToken(token);
    if (!user) {
      ws.send(JSON.stringify({
        type: 'error',
        data: { message: '无效的认证token' }
      }));
      ws.close();
      return;
    }

    // 从数据库获取用户的完整信息，包括nickname和avatar
    const [userInfo] = await pool.query(
      'SELECT id, email, username, nickname, avatar, role FROM users WHERE id = ?',
      [user.id]
    ) as [RowDataPacket[], any];

    if (userInfo.length === 0) {
      ws.send(JSON.stringify({
        type: 'error',
        data: { message: '用户不存在' }
      }));
      ws.close();
      return;
    }

    const userDetails = userInfo[0];
    const displayName = userDetails.nickname || userDetails.username || userDetails.email;
    
    // 检查用户角色，确定是否为管理员
    const isAdmin = userDetails.role === 'admin';
    console.log(`用户连接 - ID: ${userDetails.id}, 显示名: ${displayName}, 角色: ${userDetails.role}, 是否为管理员: ${isAdmin}`);

    // 添加用户到聊天管理器，并传入完整用户信息用于通知
    chatManager.addUser(ws, userDetails.id, displayName, isAdmin, {
      nickname: userDetails.nickname,
      avatar: userDetails.avatar
    });

    // 发送连接成功消息
    const unreadCount = await getUnreadCount(userDetails.id);
    chatManager.sendToUser(ws, {
      type: 'user_info',
      data: {
        message: isAdmin ? '管理员已连接到聊天系统' : '欢迎使用聊天功能',
        userId: userDetails.id,
        userName: displayName,
        nickname: userDetails.nickname,
        avatar: userDetails.avatar,
        isAdmin,
        unreadCount,
        stats: chatManager.getStats()
      }
    });

    // 处理消息
    ws.on('message', async (data: Buffer) => {
      try {
        const message: WebSocketMessage = JSON.parse(data.toString());
        const currentUser = chatManager.getUser(ws);
        if (!currentUser) return;
        switch (message.type) {
          case 'message':
            // 普通聊天消息
            const targetUserId = message.targetUserId;
            console.log(`收到消息 - 发送者: ${currentUser.userName} (${currentUser.isCustomerService ? 'Admin' : 'User'}), 目标用户: ${targetUserId || '广播'}, 内容: ${message.data.message}`);
            
            const chatMessage = {
              type: 'message' as const,
              data: {
                message: message.data.message,
                userId: currentUser.userId,
                userName: currentUser.userName,
                nickname: userDetails.nickname,
                avatar: userDetails.avatar,
                isAdmin: currentUser.isCustomerService,
                targetUserId: targetUserId
              },
              timestamp: Date.now(),
              targetUserId: targetUserId
            };

            // 保存到数据库
            await saveChatMessage(
              currentUser.userId, 
              message.data.message,
              currentUser.isCustomerService ? 'customer_service' : 'user',
              targetUserId
            );

            if (currentUser.isCustomerService) {
              // 管理员发送消息
              if (targetUserId) {
                // 一对一聊天：发送给指定用户
                console.log(`管理员向用户 ${targetUserId} 发送一对一消息`);
                const sent = chatManager.sendToUserId(targetUserId, chatMessage);
                if (!sent) {
                  // 用户不在线，返回离线状态
                  chatManager.sendToUser(ws, {
                    type: 'error',
                    data: { message: `用户 ${targetUserId} 当前不在线` }
                  });
                }
                
                // 同时发送给其他管理员（同步消息）
                chatManager.broadcastToAdmins(chatMessage, ws);
              } else {
                // 广播消息：发送给所有普通用户
                console.log(`管理员消息广播给 ${chatManager.getStats().normalUserCount} 个普通用户`);
                chatManager.broadcastToUsers(chatMessage);
              }
            } else {
              // 普通用户发送消息，广播给所有管理员
              console.log(`普通用户消息广播给 ${chatManager.getStats().adminCount} 个管理员`);
              chatManager.broadcastToAdmins(chatMessage);
            }
            break;

          case 'typing':
            // 正在输入状态
            const typingTargetUserId = message.targetUserId;
            const typingMessage = {
              type: 'typing' as const,
              data: {
                userId: currentUser.userId,
                userName: currentUser.userName,
                nickname: userDetails.nickname,
                avatar: userDetails.avatar,
                isAdmin: currentUser.isCustomerService,
                targetUserId: typingTargetUserId
              },
              targetUserId: typingTargetUserId
            };

            if (currentUser.isCustomerService) {
              // 管理员正在输入
              if (typingTargetUserId) {
                // 一对一聊天：通知指定用户
                chatManager.sendToUserId(typingTargetUserId, typingMessage);
              } else {
                // 广播：通知所有普通用户
                chatManager.broadcastToUsers(typingMessage);
              }
            } else {
              // 普通用户正在输入，通知所有管理员
              chatManager.broadcastToAdmins(typingMessage);
            }
            break;

          case 'stop_typing':
            // 停止输入状态
            const stopTypingTargetUserId = message.targetUserId;
            const stopTypingMessage = {
              type: 'stop_typing' as const,
              data: {
                userId: currentUser.userId,
                userName: currentUser.userName,
                nickname: userDetails.nickname,
                avatar: userDetails.avatar,
                isAdmin: currentUser.isCustomerService,
                targetUserId: stopTypingTargetUserId
              },
              targetUserId: stopTypingTargetUserId
            };

            if (currentUser.isCustomerService) {
              // 管理员停止输入
              if (stopTypingTargetUserId) {
                // 一对一聊天：通知指定用户
                chatManager.sendToUserId(stopTypingTargetUserId, stopTypingMessage);
              } else {
                // 广播：通知所有普通用户
                chatManager.broadcastToUsers(stopTypingMessage);
              }
            } else {
              // 普通用户停止输入，通知所有管理员
              chatManager.broadcastToAdmins(stopTypingMessage);
            }
            break;

          case 'read_message':
            // 标记消息为已读
            const messageIds = message.data.messageIds;
            await markMessagesAsRead(currentUser.userId, messageIds);
            
            // 获取最新的未读数量
            const newUnreadCount = await getUnreadCount(currentUser.userId);
            
            // 通知当前用户未读数量更新
            chatManager.sendToUser(ws, {
              type: 'message_read',
              data: {
                unreadCount: newUnreadCount,
                readMessageIds: messageIds
              }
            });
            break;

          case 'ping':
            // 处理ping消息，保持连接活跃
           // console.log('🏓 收到WebSocket ping消息，保持连接活跃');
            chatManager.sendToUser(ws, {
              type: 'pong',
              data: { message: 'pong', timestamp: Date.now() }
            });
            break;

          case 'pong':
            // 处理pong响应
          //console.log('🏓 收到WebSocket pong响应');
            break;

          // AI聊天请求现在通过POST /api/aiChat/stream 接口处理
          // WebSocket只用于接收实时回复

          default:
            console.log('❓ 未知WebSocket消息类型:', message.type);
        }

        // 更新用户活跃时间
        currentUser.lastActivity = Date.now();

      } catch (error) {
        console.error('处理WebSocket消息失败:', error);
        chatManager.sendToUser(ws, {
          type: 'error',
          data: { message: '消息处理失败' }
        });
      }
    });
    
    // 处理连接关闭
    ws.on('close', () => {
      chatManager.removeUser(ws);
      console.log('WebSocket连接已关闭');
    });

    // 处理连接错误
    ws.on('error', (error: Error) => {
      console.error('WebSocket错误:', error);
      chatManager.removeUser(ws);
    });
  });

  // 定期清理非活跃连接
  setInterval(() => {
    const timeout = 5 * 60 * 1000; // 5分钟超时

    // 清理非活跃连接
    const cleanedCount = chatManager.cleanupInactiveConnections(timeout);
    
    // 额外清理断开的连接
    const deadConnections = chatManager.cleanupDeadConnections();
    
    if (cleanedCount > 0 || deadConnections > 0) {
      console.log(`连接清理完成 - 非活跃: ${cleanedCount}, 断开: ${deadConnections}, 当前在线: ${chatManager.getStats().totalUsers}`);
    }
  }, 60000); // 每分钟检查一次

  console.log('WebSocket服务器已启动，路径: /websocket');
  return wss;
}

export { chatManager }; 